<?php

namespace App\Trip\Plane\Variflight\Result;

use App\Models\Plane\Comfort\PlaneComfort;
use App\Models\Plane\Flight\FlightCabin;
use App\Trip\Plane\Cabin\CabinClass;

class ComfortResultLocal implements ComfortResultInterface
{
    private PlaneComfort $comfort_info;

    public function __construct(PlaneComfort $comfort_info)
    {
        $this->comfort_info = $comfort_info;
    }

    public function findOneByFlightNo(string $flight_no): array
    {
        $base   = $this->comfort_info->toArray();
        $fc     = new FlightCabin();
        $cabins = collect($fc->listByFlight($this->comfort_info->flight_no))->pluck('type', 'cabin')->toArray();
        // 这里需要洗一下数据  group by 经济舱/头等舱
        $ec_count       = 0;
        $first_count    = 0;
        $db_cabins      = $this->comfort_info->cabins;
        $base['cabins'] = collect($db_cabins)->map(function ($cabin) use ($cabins, &$ec_count, &$first_count) {
            $cabin_show = [
                'cabin_name',
                'cabin_name_uy',
                'cabin',
                'seat_space',
                'seat_width',
                'seat_tilt',
                'meal',
                'meal_type',
                'has_media',
                'media',
                'has_power',
                'power',
                'has_wifi',
                'wifi',
            ];
            $cabin_code = $cabin['cabin'];
            $match      = $cabins[$cabin_code] ?? false;
            if (!$match) {
                return false;
            }
            if ($match == CabinClass::ECONOMY_CODE && $ec_count == 0) {
                $ec_count               = 1;
                $cabin['cabin_name']    = CabinClass::ECONOMY;
                $cabin['cabin_name_uy'] = trans2uy(CabinClass::ECONOMY);
                return collect($cabin)->only($cabin_show)->toArray();
            } elseif ($match == CabinClass::FIRST_CODE && $first_count == 0) {
                $first_count            = 1;
                $cabin['cabin_name']    = CabinClass::FIRST;
                $cabin['cabin_name_uy'] = trans2uy(CabinClass::FIRST);
                return collect($cabin)->only($cabin_show)->toArray();
            } else {
                return false;
            }
        })->filter()->toArray();
        return $base;
    }
}